/**
 * Makes sure that user logs in with the correct credentials. 
 */
package docoffice.doss;
import java.sql.ResultSet;
import java.util.logging.Logger;

import docoffice.database.DatabaseManager;


/**
 * 
 * @author David Garcia
 * @version $Revision: 1.0 $
 */
public class Authentication {
	
	/**
	 * Field attempts.
	 */
	private int attempts;
	
	/**
	 * Field MAXATTEMPTS.
	 */
	private static final int MAXATTEMPTS = 3;
	
	/**
	 * Field LOG.
	 */
	private static final Logger LOG = Logger.getLogger("Authentication");
	
	/**
	 * Constructor for Authentication.
	 */
	public Authentication(){
		attempts = 0;
	}
	
	/**
	 * Method authenticate.
	 * @param username String
	 * @param password String
	
	 * @return boolean */
	public String authenticate(String username, String password){
		boolean isLocked = isAccountLocked(username);
		boolean authenticated = false;
		String userType = "None";
		attempts++;
		final DatabaseManager dbMgr = new DatabaseManager();
		ResultSet rs = null;
		final String sqlQuery = "SELECT UserType FROM login WHERE Username = '" + username 
			+ "' AND Password = '" + password + "'";
		if(!isLocked){
			try{
				rs = dbMgr.runReadQuery(sqlQuery);
				if (rs.first()){
					userType = rs.getString("UserType");
				}
			} catch(Exception e){
				LOG.severe("A SQL Error occured while trying to login");
				e.printStackTrace();
			} finally{
				dbMgr.closeConnection(rs);
			}
			
			if ((!authenticated) && (attempts >= MAXATTEMPTS)){
				lockUser(username);
			}
		}
		return userType;
	}
	
	/**
	 * Method lockUser.
	 * @param username String
	 */
	public void lockUser(String username){
		final DatabaseManager dbMgr = new DatabaseManager();
		final String sqlQuery = "UPDATE login SET isLocked = 1 WHERE Username = '" 
			+ username + "'";
		
		try{
			dbMgr.runUpdateQuery(sqlQuery);
		} catch(Exception e){
			LOG.severe("A SQL error occurred while locking user account");
			e.printStackTrace();
		} finally{
			dbMgr.closeConnection();
		}
		LOG.info("User account has been locked after 3 unsuccessful attempts");
	}
	
	/**
	 * Method isAccountLocked.
	 * @param username String
	 * @return boolean
	 */
	public boolean isAccountLocked(String username){
		boolean isLocked = false;
		final DatabaseManager dbMgr = new DatabaseManager();
		final String sqlQuery = "SELECT isLocked FROM login WHERE Username = '" + username + "'";
		ResultSet rs = null;
		
		try{
			rs = dbMgr.runReadQuery(sqlQuery);
			rs.first();
			isLocked = rs.getBoolean("isLocked");
		} catch(Exception e){
			e.printStackTrace();
		} finally{
			dbMgr.closeConnection(rs);
		}
		
		return isLocked;
	}
	
	/**
	 * Method toString.
	
	 * @return String */
	public String toString(){
		return "This class handles the authentication process";
	}
}
